<template>
  <div class="subscription-container">
    <h2>选择会员等级</h2>
    <div class="plan-cards">
      <div v-for="plan in plans" :key="plan.level" class="plan-card">
        <h3>{{ plan.name }}</h3>
        <p>白名单数量：{{ plan.whitelistLimit }}</p>
        <p>价格：<strong>{{ plan.monthlyPrice }} 元/月</strong></p>
        <button @click="subscribe(plan)">立即订阅</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';

const plans = ref([]);

onMounted(async () => {
  try {
    const res = await axios.get('/api/subscriptions/plans/1');
    // 获取所有等级（这里只是示例）
    plans.value = [
      { level: 1, name: '基础版', whitelistLimit: 3, monthlyPrice: 0 },
      { level: 2, name: '标准版', whitelistLimit: 20, monthlyPrice: 100 },
      { level: 3, name: '高级版', whitelistLimit: 100, monthlyPrice: 300 }
    ];
  } catch (err) {
    console.error('获取套餐失败:', err);
  }
});

const subscribe = async (plan) => {
  try {
    const res = await axios.get('/api/wechatpay/prepay', {
      params: {
        userId: 'test_user_id',
        planLevel: plan.level
      }
    });

    if (window.WeixinJSBridge) {
      window.WeixinJSBridge.invoke(
        'getBrandWCPayRequest',
        {
          "appId": res.data.appId,
          "timestamp": res.data.timestamp,
          "nonceStr": res.data.nonceStr,
          "package": res.data.package,
          "signType": res.data.signType,
          "paySign": res.data.paySign
        },
        function (res) {
          if (res.err_msg === 'get_brand_wcpay_request:ok') {
            alert('支付成功！');
          } else {
            alert('支付失败，请重试');
          }
        }
      );
    } else {
      alert('请在微信浏览器中打开此页面以进行支付');
    }
  } catch (err) {
    console.error('发起支付失败:', err);
    alert('发起支付失败，请稍后再试');
  }
};
</script>

<style scoped>
.subscription-container {
  padding: 20px;
}
.plan-cards {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
}
.plan-card {
  border: 1px solid #ddd;
  padding: 20px;
  border-radius: 8px;
  width: 250px;
  text-align: center;
}
.plan-card h3 {
  margin-top: 0;
}
button {
  padding: 10px 15px;
  background-color: #722ed1;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
button:hover {
  background-color: #531dab;
}
</style>